import 'package:banner_carousel/banner_carousel.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:mokeng/utils/extension.dart';
import 'package:mokeng/values/values.dart';
import 'package:mokeng/widgets/get_view_keep_alive.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'index.dart';

class StoreRecommendView extends GetViewKeepAlive<TransItemController> {
  final dynamic value;

  StoreRecommendView({super.key, super.tag, required this.value}) {
    Get.put(TransItemController(value: value), tag: tag);
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      enablePullUp: true,
      physics: const BouncingScrollPhysics(),
      controller: controller.refreshController,
      onRefresh: controller.onRefresh,
      onLoading: controller.onLoading,
      child: CustomScrollView(
        physics: const BouncingScrollPhysics(),
        slivers: [
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return Obx(() {
                  Widget widget = 1.vGap;
                  int styleType = value['floorList'][index]['styleType']; //楼层id
                  if (controller.headerData.value.containsKey(styleType)) {
                    dynamic floorData = controller.headerData.value[styleType];
                    if (styleType == 1) {
                      //Banner类型
                      widget = _widgetFloorBanner(floorData);
                    } else if (styleType == 19) {
                      //图标指示器类型
                      widget = _widgetFloorIcon(floorData);
                    }
                  }
                  return widget;
                });
              },
              childCount: value['floorList'].length,
            ),
          ),
          Obx(
            () => controller.productList.isEmpty
                ? SliverToBoxAdapter(
                    child: SizedBox(
                      height: 200.h,
                      child: const Center(
                        child: Text('暂无数据'),
                      ),
                    ),
                  )
                : SliverPersistentHeader(
                    pinned: true,
                    delegate: HeaderDelegate(
                      minHeight: 40.0,
                      maxHeight: 40.0,
                      child: Container(
                        color: AppColors.scaffoldBackground,
                        alignment: Alignment.center,
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: Row(
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            Expanded(
                              child: DropdownButtonHideUnderline(
                                child: DropdownButton2<DropdownItemOption>(
                                  valueListenable: controller.selectedSort,
                                  hint: Text(
                                    '排序',
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: Theme.of(context).hintColor,
                                    ),
                                  ),
                                  items: controller.sortList
                                      .map((e) => DropdownItem(
                                            value: e,
                                            height: 40,
                                            child: Text(e.label), // 显示值
                                          ))
                                      .toList(),
                                  onChanged: (newValue) {
                                    controller.selectedSort.value = newValue!;
                                    controller.onRefresh();
                                  },
                                  alignment: AlignmentDirectional.centerEnd,
                                ),
                              ),
                            ),
                            Expanded(
                              child: DropdownButtonHideUnderline(
                                child: DropdownButton2<DropdownItemOption>(
                                  valueListenable: controller.selectedSort,
                                  hint: Text(
                                    '排序',
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: Theme.of(context).hintColor,
                                    ),
                                  ),
                                  items: controller.sortList
                                      .map((e) => DropdownItem(
                                            value: e,
                                            height: 40,
                                            child: Text(e.label), // 显示值
                                          ))
                                      .toList(),
                                  onChanged: (newValue) {
                                    controller.selectedSort.value = newValue!;
                                    controller.onRefresh();
                                  },
                                  alignment: AlignmentDirectional.centerEnd,
                                ),
                              ),
                            ),
                            30.vGap,
                          ],
                        ),
                      ),
                    ),
                  ),
          ),
          Obx(() {
            return SliverToBoxAdapter(
              child: value['name'] == "推荐"
                  ? ListView.builder(
                      itemCount: controller.productList.length,
                      shrinkWrap: true, // 防止 ListView 自身滚动
                      physics: const NeverScrollableScrollPhysics(), // 禁止 ListView 自身滚动
                      itemBuilder: (BuildContext context, int index) {
                        return StoreItemRecommend(productData: controller.productList[index]);
                      },
                    )
                  : MasonryGridView.count(
                      padding: EdgeInsets.zero,
                      crossAxisCount: 2,
                      mainAxisSpacing: 4,
                      crossAxisSpacing: 4,
                      shrinkWrap: true, // 防止 ListView 自身滚动
                      physics: const NeverScrollableScrollPhysics(), // 禁止 ListView 自身滚动
                      itemBuilder: (context, index) {
                        var item = controller.productList[index];
                        return Image.network(
                          item['avatar'],
                          height: 204 * num.parse(item['coverHeight']) / num.parse(item['coverWidth']),
                          fit: BoxFit.cover,
                        );
                      },
                      itemCount: controller.productList.length,
                    ),
            );
          }),
        ],
      ),
    );
  }

  Widget _widgetFloorBanner(dynamic bannerData) {
    Get.log('接收到Banner数据：$bannerData');
    if (bannerData is! List) return 1.vGap;
    return BannerCarousel(
      banners: bannerData.map((element) {
        return BannerModel(imagePath: element['imgUrl'], id: element['id']);
      }).toList(),
      showIndicator: false,
    );
  }

  Widget _widgetFloorIcon(dynamic iconData) {
    if (iconData is! String) return 1.vGap;
    return Container(
      height: 50.h,
      margin: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.red,
        borderRadius: 7.radius,
      ),
      child: Center(
        child: Text(iconData),
      ),
    );
  }
}

class HeaderDelegate extends SliverPersistentHeaderDelegate {
  final double minHeight;
  final double maxHeight;
  final Widget child;

  HeaderDelegate({
    required this.minHeight,
    required this.maxHeight,
    required this.child,
  });

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return child;
  }

  @override
  double get maxExtent => maxHeight;

  @override
  double get minExtent => minHeight;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}
